import sys
from confs import EBV_SHARP_ADDITION
from ebv_iterate_utils import read_stats

# removes tokens in dl, dr from links
def links_delta(links, dl, dr):
    if not dl and not dr:
        return ' '.join(links)

    dl = set(dl)
    dr = set(dr)

    res = []
    degl = degr = 0
    for token in links:
        if token == '<' or token == '>':
            res.append(token)
        else:
            key, val = token.split(':')
            if key == 'l':
                if val not in dl:
                    degl += 1
                    res.append(token)
            elif key == 'r':
                if val not in dr:
                    degr += 1
                    res.append(token)
    return ' '.join(['degl:%d' % degl, 'degr:%d' % degr] + res)

def output(word, lbv, rbv, links, dl, dr, sls, srs):
    if word and links:
        lbv /= 1.0 + sls * EBV_SHARP_ADDITION
        rbv /= 1.0 + srs * EBV_SHARP_ADDITION
        links = links_delta(links, dl, dr)
        print '%s\tlbv:%s rbv:%s %s' % (word, lbv.hex(), rbv.hex(), links)

def main():
    '''
    output: ebv_iteration_<i>.txt where i is current iteration id
    (word, 'lbv+:'lbv.., 'rbv+:'rbv.., '<'? '>'? degl degr llinkees.. rlinkees.. 'l-:'llinkees.. 'r-:'rlinkees..) ->
        (word, sum-of-lbv sum-of-rbv '<'? '>'? new-degl new-degr new-llinkees.. new-rlinkees..)
        where new-llinkees = llinkees - 'l-:'llinkees
              new-rlinkees = rlinkees - 'r-:'rlinkees
    '''
    words, sharpls, sharprs = read_stats()
    prev_word = ''
    lbv = rbv = 0.0
    links = []
    dl = []
    dr = []
    for line in sys.stdin:
        line = line.strip()
        tokens = line.split()
        word = tokens[0]
        if word != prev_word:
            output(prev_word, lbv, rbv, links, dl, dr, sharpls, sharprs)
            lbv = rbv = 0.0
            links = []
            dl = []
            dr = []
        prev_word = word

        if len(tokens) == 2:
            key, val = tokens[1].split(':')
            if key == 'lbv+':
                lbv += float.fromhex(val)
            elif key == 'rbv+':
                rbv += float.fromhex(val)
            elif key == 'l-':
                dl.append(val)
            elif key == 'r-':
                dr.append(val)
        elif len(tokens) > 2:
            links = tokens[1: ]
    output(prev_word, lbv, rbv, links, dl, dr, sharpls, sharprs)

if __name__ == '__main__':
    main()
